package com.lyn.fileplus;



import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件夹工厂
 * @author Lyn 2022/12/18
 * @version 1.0.0
 */
public class FolderCore implements Folder {

    private final String path;

    public FolderCore(String path) {
        if (TextUtils.isEmpty(path)){
            throw new NullPointerException("路径不能为空!");
        }
        this.path = path;
        File file = new File(path);
        if (!file.exists()){
            boolean mkdirs = file.mkdirs();
            if (!mkdirs){
                throw new Error("文件夹创建失败!");
            }
        }
    }


    @Override
    public String getPath() {
        return this.path;
    }

    @Override
    public String saveFile(File file) {
       return FileUtil.copyFileToFolder   (file,this.path);
    }

    @Override
    public String saveFile(InputStream in, String fileName) {
        return FileUtil.copyFileToFolder(in,fileName,this.path);
    }

    @Override
    public boolean deleteFile(String fileName) {
        return FileUtil.deleteFile(new File(this.path,fileName).getAbsolutePath());
    }

    @Override
    public File getFile(String fileName) {
        File file = new File(this.path, fileName);
        if (file.exists()&&file.isFile()){
            return file;
        }
        return null;
    }

    @Override
    public File[] getFiles() {
        return new File(path).listFiles();
    }

    @Override
    public boolean deleteAllFile() {
        File file = new File(this.path);
        if (file.exists()&&file.isDirectory()){
            File[] files = file.listFiles();
            assert files != null;
            for (File itemFile:files){
                if (itemFile.isFile()){
                    FileUtil.deleteFile(itemFile.getAbsolutePath());
                }else {
                    FileUtil.deleteFolder(itemFile.getAbsolutePath());
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public FileInputStream getFileInputStream(String fileName) {
        try {
            return new FileInputStream(new File(this.path,fileName));
        }catch (Throwable e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String saveTxt(String text) {
        return FileUtil.saveTxt(text, this.path, UUID.randomUUID().toString().concat(".txt"), false);
    }

    @Override
    public String saveTxt(String text, String fileName) {
        return FileUtil.saveTxt(text, this.path, fileName, false);
    }

    @Override
    public String saveTxt(String text, String fileName, boolean append) {
        return FileUtil.saveTxt(text, this.path, fileName, append);
    }

    @Override
    public String readTxt(String fileName) {
        return FileUtil.readTxt(this.path.concat("/").concat(fileName));
    }
}
